<template>
  <div class="userlist-wrap">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-cascader style="width: 100%" @change="changeselect"
                     :options="options" clearable
                     v-model="categoryData"
                     :props="{label: 'title', value: 'id' }"></el-cascader>
      </el-col>
      <el-col :span="5">
        <el-input v-model="keyword" @keyup.enter.native="onSubmit" placeholder="请输入查询内容"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button @click="onSubmit" type="primary" icon="el-icon-search">搜索</el-button>
        <el-button @click="add_article" type="primary" icon="el-icon-plus">添加</el-button>
      </el-col>
    </el-row>
    <el-table
            :data="tableData"
            border
            style="margin: 22px 0;"
            class="table"
            ref="multipleTable"
            header-cell-class-name="table-header"
    >
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>


      <el-table-column label="头像(查看大图)" align="center">
        <template slot-scope="scope">
          <el-image
                  style="width: 60px;height: 60px;"
                  :src="scope.row.image"
                  :preview-src-list="[scope.row.image]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者" align="center"></el-table-column>
      <el-table-column prop="cate_gory.title" label="分类" align="center"></el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div @click="article_id = scope.row.id">
            <el-switch
                    @change="switch_change(scope.row)"
                    active-value="1"
                    inactive-value="0"
                    v-model="scope.row.status"
                    active-text="启动"
                    inactive-text="禁用">
            </el-switch>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="created_at" width="180" label="注册时间" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button
                  type="warning"
                  icon="el-icon-edit"
                  class="red"
                  @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="query.page"
            :page-size="query.limit"
            :total="query.total"
            @current-change="handlePageChange"
    ></el-pagination>

    <el-dialog
            :title="dialogTitle" top="2vh"
            :visible.sync="dialogVisible"
            width="50%"
            :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="图片" prop="image">
          <el-upload
                  class="avatar-uploader"
                  action="http://api.qiangongzaowu.com/api/file_upload"
                  :show-file-list="false"
                  accept=".jpg, .png, .jpeg"
                  :before-upload="beforeUp"
                  :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.image" :src="ruleForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章名称" prop="title">
          <el-input style="width: 40%;" placeholder="请输入文章名称" v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作者名称" prop="author">
          <el-input style="width: 40%;" placeholder="请输入作者名称" v-model="ruleForm.author"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="total_fee" v-if="priceShow">
          <el-input style="width: 40%;" placeholder="请输入价格" type="number" v-model="ruleForm.total_fee"></el-input>
        </el-form-item>
        <el-form-item label="文章类别" prop="category_id">
          <el-cascader style="width: 40%" @change="categoryChange"
                       :options="options"
                       v-model="ruleForm.category_id"
                       :props="{label: 'title', value: 'id' }"></el-cascader>
        </el-form-item>
        <el-form-item class="text-area-wrap" label="文章介绍" prop="text">
          <editor ref="editorComponent" :value="ruleForm.text" @textChange="getMsgFormSon"></editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确 认</el-button>
          <el-button @click="exitAdd">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { Message } from 'element-ui'
  import editor from './Quilleditor'
  export default {
    name: 'userlist',
    data () {
      return {
        priceShow: false,
        articleId: '',
        dialogTitle: '添加文章',
        dialogVisible: false,
        ruleForm: {
          text: '',
          category_id: '',
          title: '',
          author: '',
          image: '',
          total_fee: ''
        },
        rules: {
          title: [
            { required: true, message: '请输入文章名称', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          text: [
            { required: true, message: '请输入文章介绍', trigger: 'blur' }
          ],
          total_fee: [
            { required: true, message: '请输入价格', trigger: 'blur' }
          ],
          author: [
            { required: true, message: '请输入作者名称', trigger: 'blur' }
          ],
          category_id: [
            { required: true, message: '请选择文章类别', trigger: 'change' }
          ],
          image: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ],
        },
        // ///////////
        categoryData: [],
        options: [],
        article_id: '',
        keyword: '',
        category_id: '',
        tableData: [],
        query: {
          limit: 10,
          page: 2
        },
        page: 1
      }
    },
    components: {
      editor
    },
    methods: {
       compressFile(file,callback) {
    let fileObj = file;
    let reader = new FileReader()
    reader.readAsDataURL(fileObj) //转base64
    reader.onload = function(e) {
      let image = new Image() //新建一个img标签（还没嵌入DOM节点)
      image.src = e.target.result
      image.onload = function () {
        let canvas = document.createElement('canvas'), // 新建canvas
          context = canvas.getContext('2d'),
          imageWidth = image.width / 9,    //压缩后图片的大小
          imageHeight = image.height / 9,
          data = ''
        canvas.width = imageWidth
        canvas.height = imageHeight
        context.drawImage(image, 0, 0, imageWidth, imageHeight)
        data = canvas.toDataURL('image/jpeg') // 输出压缩后的base64
        let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], // 转成blob
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        let files = new window.File([new Blob([u8arr], {type: mime})], 'test.jpeg', {type: 'image/jpeg'}) // 转成file
        callback(files) // 回调
      }
    }
  },
      beforeUp(file) {
        if (file.size / 1024 /1024 > 2) {
          let _this = this
          return new Promise((resolve, reject) => {
            let isLt2M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于10MB11111
            if(!isLt2M) {
              reject()
            }
            let image = new Image(), resultBlob = '';
            image.src = URL.createObjectURL(file);
            image.onload = () => {
              // 调用方法获取blob格式，方法写在下边
              resultBlob = _this.compressUpload(image, file);
              resolve(resultBlob)
            }
            image.onerror = () => {
              reject()
            }
          })
        } else {
          return new Promise(resolve => {
            resolve(file)
          })
        }


      },

      compressUpload(image, file) {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let initSize = image.src.length
        let { width } = image, { height } = image
        canvas. width = width
        canvas.height = height
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(image, 0, 0, width, height)

        // 进行最小压缩0.1
        let compressData = canvas.toDataURL(file.type || 'image/jpeg', 0.1)

        // 压缩后调用方法进行base64转Blob，方法写在下边
        let blobImg = this.dataURItoBlob(compressData)
        return blobImg
      },

      /* base64转Blob对象 */
      dataURItoBlob(data) {
        let byteString;
        if(data.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(data.split(',')[1])
        }else {
          byteString = unescape(data.split(',')[1])
        }
        let mimeString = data
          .split(',')[0]
          .split(':')[1]
          .split(';')[0];
        let ia = new Uint8Array(byteString.length)
        for( let i = 0; i < byteString.length; i += 1) {
          ia[i] = byteString.charCodeAt(i)
        }
        return new Blob([ia], {type: mimeString})
      },
      changeselect(item) {
        this.page = 1
        this.pub()
      },
      categoryChange(item) {
        if (item[0] < 3) {
          this.priceShow = true
        } else {
          this.priceShow = false
          this.ruleForm.total_fee = 0
        }
      },
      handleEdit (row) {
        this.$http.get('api/admin/article/Article/' + row.id).then(r => {
          this.articleId = r.data.data.id
          this.ruleForm.title = r.data.data.title
          this.ruleForm.image = r.data.data.image
          this.ruleForm.author = r.data.data.author
          this.ruleForm.total_fee = r.data.data.total_fee
          if (r.data.data.total_fee > 0) {
            this.priceShow = true
          }
          this.ruleForm.text = r.data.data.text
          bbq:
            for(var j=0;j<this.options.length;j++){
              ccc:
                for(var i =0;i<this.options[j].children.length;i++){
                  console.log(this.options[j].children[i].id, r.data.data.category_id)
                  if( this.options[j].children[i].id === r.data.data.category_id ){
                    this.categoryData = [this.options[j].id, r.data.data.category_id]
                    break bbq; //直接跳出bbq外层循环
                  }
                }
            }
          this.ruleForm.category_id = this.categoryData
          this.dialogVisible = true
          this.dialogTitle = '编辑文章'
          setTimeout(() => {
            this.$refs.editorComponent.value = r.data.data.text
          }, 1000)

        })
      },
      exitAdd () {
        this.ruleForm = {
          text: '',
            category_id: '',
            title: '',
            author: '',
            image: '',
          total_fee: ''
        }
        // this.categoryData = ''
        this.$refs.editorComponent.value = ''
        this.$refs['ruleForm'].resetFields();
        this.dialogVisible = false
      },
      handleClose (d) {
        this.ruleForm = {
          text: '',
          category_id: '',
          title: '',
          author: '',
          image: '',
          total_fee: ''
        }
        // this.categoryData = ''
        this.$refs.editorComponent.value = ''
        this.$refs['ruleForm'].resetFields();
        d()
      },
      // 图片上传回调
      getMsgFormSon(data){
        this.ruleForm.text = data
      },
      handleAvatarSuccess (file) {
        this.ruleForm.image = file.data.path
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              if (this.ruleForm.total_fee <= 0 && this.ruleForm.category_id[0] < 3){
                Message.error('价格必须大于0')
                return false
              }
              // if (this.ruleForm.category_id[0] > 2) {
              //   delete this.ruleForm.total_fee
              // }
              this.ruleForm.category_id = this.ruleForm.category_id[1]
              if (this.articleId) {
                // 编辑
                this.$http.put('api/admin/article/Article/' + this.articleId, this.ruleForm).then(r => {
                  Message.success('文章编辑成功...')
                  this.exitAdd()
                  this.pub()
                  this.priceShow = false
                })
              } else {
                this.$http.post('api/admin/article', this.ruleForm).then(r => {
                  Message.success('文章添加成功...')
                  this.exitAdd()
                  this.pub()
                  this.priceShow = false
                })
              }



          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      onSubmit () {
        this.page = 1
        this.pub()
      },
      add_article () {
        this.dialogVisible = true
        this.articleId = ''
      },
      handlePageChange (page) {
        this.page = page
        this.pub()
      },
      updateStatus (row) {
        this.$http.put('status/User/' + row.id, {params: {status: row.status == 1 ? 0 : 1}}).then(r =>{

        })
      },
      switch_change (row) {
        this.$http.put('api/admin/article/status/Article/' + row.id, {status: row.status}).then(r => {
        })
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('api/admin/article/Article/' + row.id).then(r =>{
            this.$message({
              type: 'success',
              message: '文章删除成功!'
            });
            this.pub()
          })

        })

      },
      pub() {
        let params = {
          keyword: this.keyword,
          category_id: this.categoryData.length > 0 ? this.categoryData[1]: '',
          page: this.page
        }
        this.$http.get('api/admin/article', {params}).then(r => {
          this.tableData = r.data.data.data.data
          this.tableData.forEach(item => {
            item.status = item.status + ''
          })
          this.query = r.data.data.meta
        })
      }
    },
    created () {
      this.pub()
      this.$http.get('api/cate/nav').then(r => {
        this.options = r.data.data
      })
    }
  }
</script>

<style scoped lang="less">
  .userlist-wrap{
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ddd;
    padding: 30px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
  }
</style>
<style lang="less">
  .table-header{
    font-weight: bold;
  }
  .text-area-wrap strong{
    font-weight: bold !important;
  }
  .text-area-wrap em{
    font-style: italic !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
</style>
<style lang="less">
  .tag-label{
    cursor: pointer;
  }
</style>
